package day21.pack2;

import day20.pack1.Counter;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class Sell extends Thread {
    private static final Unsafe unsafe;
    private static final long memoryAddress;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
            Field addressFile = Repository.class.getDeclaredField("count");
            memoryAddress = unsafe.objectFieldOffset(addressFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private String type; // 线上/线下
    private Repository repository; // 仓库
    public Sell(Repository repository, String type) {
        this.repository = repository;
        this.type = type;
    }
    public void run() {
        while(repository.getCount() > 0) {
            int oldVal = repository.getCount();
            int newVal = repository.getCount() - 1;
            while (unsafe.compareAndSwapInt(repository, memoryAddress, oldVal, newVal)) {
                System.out.println("[" + type + "]成功购买了第：【" + (10001 - oldVal) + "】台游戏机!");
            }
        }
    }
}
